import VueRouter from "vue-router";
import pageFrame from "_c/pageFrame/pageFrame.vue";
import Token from "@/utils/token";



// 解决连续多次点击路由报错问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

const routes = [
  {
    path: "/login",
    component: pageFrame,
    children: [
      {
        path: "",
        name: "login",
        meta: {
          title: "登录",
          navOther: true,
          navIndex: 0,
        },
        component: () => import("./views/login/login.vue")
      },
      {
        path: "re",
        name: "register",
        meta: {
          title: "注册",
          navOther: true,
          navIndex: 0,
        },
        component: () => import("./views/register/register.vue")
      },
      {
        path: "forget",
        name: "forget",
        meta: {
          title: "找回密码",
          navOther: true,
          navIndex: 0,
        },
        component: () => import("./views/forget/forget.vue")
      },
      {
        path: "emailc",
        name: "emailc",
        meta: {
          title: "邮箱认证",
          navOther: true
        },
        component: () => import("./views/emailc/emailc.vue")
      }
    ]
  },
  // 错误页面
  {
    path: "*",
    name: "error_404",
    meta: {
      title: "页面不存在"
    },
    component: () => import("@/mixins/error/404.vue")
  },
  {
    path: "*",
    name: "error_401",
    meta: {
      title: "没有访问权限"
    },
    component: () => import("@/mixins/error/401.vue")
  }
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const url = window.location.hostname.replace('www.', '');
  // token相关
  const token = Token.get();
  // 路由排错
  if (to.matched.length === 0) {
    // 匹配前往的路由不存在
    from.name
      ? next({
        name: from.name
      })
      : next({
        name: "error_404"
      }); // 判断此跳转路由的来源路由是否存在，存在的情况跳转到来源路由，否则跳转到404页面
  } else {
    if (token && to.name != "emailc") {
      window.location.href = "/";
    } else {
      next();
      // 路由发生变化修改页面title
      if (to.meta.title) {
        document.title = `${to.meta.title} - ` + url;
      }
    }
  }
});

router.afterEach(() => {
  window.scrollTo(0, 0);
});

export default router;
